package com.maegul.data.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.maegul.data.dao.AbstractDAO;
import com.maegul.data.entities.User;

@Repository(value = "userDao")
public class UserDaoImpl extends AbstractDAO<User> implements UserDao {

	@PersistenceContext(type = PersistenceContextType.EXTENDED)
	private EntityManager em;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.maegul.data.dao.DAO#getEntityManager()
	 */
	public EntityManager getEntityManager() {
		return em;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.maegul.data.dao.DAO#getClazz()
	 */
	public Class<User> getClazz() {
		return User.class;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.maegul.data.dao.impl.UserDao#findByUsername(java.lang.String)
	 */
	public User findByUsername(String username) {
		Query q = getEntityManager().createQuery(
				"from " + getClazz().getSimpleName()
						+ " u where u.username = ?1");
		q.setParameter(1, username);

		return (User) q.getSingleResult();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.maegul.data.dao.impl.UserDao#findByMail(java.lang.String)
	 */
	public User findByMail(String mail) {
		Query q = getEntityManager().createQuery(
				"from " + getClazz() + " u where u.mail = ?1");
		q.setParameter(1, mail);

		return (User) q.getSingleResult();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.maegul.data.dao.impl.UserDao#isAdmin(java.lang.String)
	 */
	public boolean isAdmin(String username) {
		return findByUsername(username).isAdmin();
	}
}
